<script setup lang="ts">
  import TableTemplate from './components/TableTemplate.vue';
  import BatchAddTemplate from './components/batchAddTemplate.vue';
  import DialogTemplate from './components/dialogTemplate.vue';
  import {ElMessage, ElMessageBox} from "element-plus";
  import {
    batchAddAccount,
    deletesAccount,
    exportFileExcel,
    getPageAccountList,
    updateAccount
  } from "../account/accountApi.js";
  const loading = ref(false)
  let dataSet = reactive({
    queryBox: [
      {
        model: 'username',
        type: 'input',
        placeholder: '请输入用户名称'
      },
      {
        model: 'sex',
        type:'select',
        placeholder: '请选择性别',
        options: [
          { label: '男', value: 0 },
          { label: '女', value: 1 },
          { label: '保密', value: 2 }
        ],
      },
      {
        model: 'status',
        type:'select',
        placeholder: '请账号选择状态',
        options: [
          { label: '启用', value: 0 },
          { label: '禁用', value: 1 },
        ],
      },
      {
        model: 'mobile',
        type: 'input',
        placeholder: '请输入手机号'
      }
    ],
    tableList: [
      {prop: 'username', label: '用户名', width: '150'},
      {prop: 'mobile', label: '手机号', width: '150'},
      {prop:'sex', label: '性别', width: '100'},
      {prop: 'email', label: '邮箱', width: '200'},
      {prop: 'creator', label: '创建者', width: '200'},
      {prop: 'createDate', label: '创建时间', width: '200'},
    ],
    tableListStutas: [
      {prop:'statuss', label: '状态', width: '120',stutasColor: 'danger'},
    ],
    tnQueryTop: [
      {name: '新增',click: 'userAdd', type: 'primary'},
      {name: '批量新增',click: 'userBatchAdd', type: 'primary'},
      {name: '批量删除',click: 'userBatchDelete', type: 'danger'},
      {name: '导出',click: 'userExport', type: 'primary'},
    ],
    operationBtns: [
      {name: '编辑', click: 'userEdit', type: 'primary'},
      {name: '删除', click: 'deleteId', type: 'danger'},
      {name: '详情', click: 'userDetail', type: 'info'},
    ],
    tableData:{
      total: 0,
      rows: []
    }
  })
//状态颜色
  const getStatusColor = (data) => {
    switch (data) {
      case '启用':
        return 'success';
      case '禁用':
        return 'primary';
      default:
        return 'info';
    }
  };
  let batchAddVisible = reactive({
    fileName: '用户批量添加Excel模板.xlsx',
    dialogFormVisibles: false,
  })
  // 弹窗 数据
  const registerDialogRef = ref(null)
  const registerTableRef = ref(null)
  const title = ref('用户新增')
  const dialogTemplateRef = ref(null)
  const dialogTemplateVisible = ref(false)
  const formItems = ref([{
    list: [
      {
        label: '用户名',
        prop: 'username',
        type: 'input',
        rules: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        placeholder: '请输入用户名'
      },
      {
        label: '手机号',
        prop: 'mobile',
        type: 'input',
        rules: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 11, max: 11, message: '长度为11位', trigger: 'blur' }
        ],
        placeholder: '请输入手机号'
      },
      {
        label: '性别',
        prop:'sex',
        type:'select',
        options: [
          { label: '男', value: 0 },
          { label: '女', value: 1 }
        ],
        placeholder: '请选择性别'
      },
      {
        label: '邮箱',
        prop: 'email',
        type: 'input',
        rules: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ],
        placeholder: '请输入邮箱'
      },
      {
        label: '状态',
        prop: 'status',
        type: 'select',
        options: [
          {label: "启用", value: 0}
          ,{label: "禁用", value: 1}
        ],
        placeholder: '请选择状态'
      },
    ]
  }])
  // 表单数据
  const initialData = ref({})
  //查看为true，其他为false
  const isViewMode = ref(false)
  // 操作名称 新增，编辑 详情
  const operationName = ref('')
  const handleDialogSubmit = async (data) => {
    data.sex=="男"?data.sex=0:data.sex=1
    data.status=="启用"?data.status=0:data.status=1
    if (operationName.value === '新增'){
      data.occupation=2
      await batchAddAccount([data]).then(res => {
        if (res.code === 0){
          ElMessage.success('新增成功')
          dialogTemplateVisible.value = false;
          dialogTemplateRef.value.dialogTemplateVisible = false;
          selectSubmit({ pageNum: 1, pageSize: 10 });
          return;
        }
        ElMessage.error(res.message || '新增失败')
      });
    }else {
      await updateAccount(data).then(res => {
        if (res.code === 0){
          ElMessage.success('编辑成功')
          dialogTemplateVisible.value = false;
          dialogTemplateRef.value.dialogTemplateVisible = false;
          selectSubmit({ pageNum: 1, pageSize: 10 });
          return;
        }
        ElMessage.error(res.message || '编辑失败')
      });
    }
  }
  // 重置
  const resetSubmit = (data) => {
    selectSubmit(data);
  }
  // 查询
  const selectSubmit = async (data) => {
    data.occupation=2;
    loading.value = true;
      await getPageAccountList(data).then(res => {

        dataSet.tableData.rows = res.data.records
        dataSet.tableData.total = res.data.total
      }).finally(() => {
        loading.value = false;
      });
  }
  selectSubmit({ pageNum: 1, pageSize: 10})
  //新增
  const userAdd = () => {
    operationName.value = '新增'
    isViewMode.value = false
    title.value = '用户新增'
    initialData.value = {}
    dialogTemplateVisible.value = true;
    dialogTemplateRef.value.dialogTemplateVisible = true;
  }
  // 批量新增
  const userBatchAdd = () => {
    batchAddVisible.dialogFormVisibles = true
  }
  const handleIndex = ref([])
  const handleChange = (data) => {
    handleIndex.value = data
  }
  // 批量删除
  const userBatchDelete = async () => {
    if (handleIndex.value.length === 0){
      ElMessage.error('请至少选择一条数据！')
      return;
    }
    ElMessageBox.confirm(
      '确定要删除这些项目吗?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {
      let ids = handleIndex.value.map(item => item.id)

      await deletesAccount(ids).then(res => {
        if (res.code === 0){
          ElMessage.success('删除成功')
          registerTableRef.value?.clearSelection();
          selectSubmit({ pageNum: 1, pageSize: 10 });
          return;
        }
        ElMessage.error(res.message || '删除失败')
        registerTableRef.value?.clearSelection();
      });
    }).catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
  }
  // 导出
  const userExport = () => {
    if (handleIndex.value.length < 1) {
      ElMessage.error("请选择要导出的数据！")
      return
    }
    exportFileExcel(handleIndex.value, '管理员');
    handleIndex.value = [];
    registerTableRef.value?.clearSelection();
  }
  // 编辑
  const userEdit = (data) => {

    operationName.value = '编辑'
    isViewMode.value = false
    title.value = '用户编辑'
    initialData.value = { ...data }
    dialogTemplateVisible.value = true;
    dialogTemplateRef.value.dialogTemplateVisible = true;
  }
  // 删除
  const deleteId = async (data) => {
    await deletesAccount([data.id]).then(res => {
      if (res.code === 0){
        ElMessage.success('删除成功')
        registerTableRef.value?.clearSelection();
        selectSubmit({ pageNum: 1, pageSize: 10 });
        return;
      }
      ElMessage.error(res.message || '删除失败')
    });
  }
  // 详情
  const userDetail = (data) => {

    operationName.value = '详情'
    isViewMode.value = true
    title.value = '用户详情'
    initialData.value = { ...data }
    dialogTemplateVisible.value = true;
    dialogTemplateRef.value.dialogTemplateVisible = true;
  }
  // 批量新增提交
  const batchAddSubmit = async (fileList, username) => {
    // 必须包含的字段
    const requiredFields = ["用户名", "手机号", "性别", "邮箱", "状态"];

    // 检查 fileList 的字段
    const isValidFile = fileList.every(item =>
      requiredFields.every(field => Object.prototype.hasOwnProperty.call(item, field))
    );

    if (!isValidFile) {
      ElMessage.error("文件格式错误，请上传正确的模板文件！");
      return;
    }
    // 构造数据
    const data = fileList.map(item => ({
      username: item.用户名,
      mobile: item.手机号,
      sex: item.性别=="男"?0:1,
      email: item.邮箱,
      status: item.状态=== "启用"?0:1,
      creator: username,
      occupation: 2,
    }));

    if (data.length < 1) {
      ElMessage.error("文件内容为空，请检查模板文件！");
      return;
    }
    //批量新增
    let response = await batchAddAccount(data);
    if (response.code === 0) {
      ElMessage.success("批量新增成功");
      batchAddVisible.dialogFormVisibles = false;
      selectSubmit({});
      return;
    }
    ElMessage.error(response.message || "批量新增失败，请检查表单");
  };




</script>

<template>
  <div class="container">
    <TableTemplate
      ref="registerTableRef"
      :data-set="dataSet"
      @userAdd="userAdd"
      @userEdit="userEdit"
      :getStatusColor="getStatusColor"
      @deleteId="deleteId"
      @userDetail="userDetail"
      @userBatchDelete="userBatchDelete"
      @userBatchAdd="userBatchAdd"
      @reset-submit="resetSubmit"
      @userExport="userExport"
      @handleChange="handleChange"
      @select-submit="selectSubmit"
      :loading="loading"
    />
    <BatchAddTemplate
      ref="registerDialogRef"
      v-model="batchAddVisible.dialogFormVisibles"
      @submit-adds="batchAddSubmit"
      @userBatchAdd="userBatchAdd"
      :batch-add-visible="batchAddVisible"
      />
    <DialogTemplate
      v-model="dialogTemplateVisible"
      ref="dialogTemplateRef"
      :title="title"
      :width="'500px'"
      :initial-data="initialData"
      :form-items="formItems"
      :is-view="isViewMode"
      @handleDialogSubmit="handleDialogSubmit"
      :operation-name="operationName"
      />
  </div>

</template>

<style scoped lang="scss">

</style>
